/*
 * @Author: panghu chenjh@datamargin.com
 * @Date: 2024-03-26 10:59:19
 * @LastEditors: panghu chenjh@datamargin.com
 * @LastEditTime: 2024-03-27 19:32:41
 * @FilePath: \vue3-vite-mall-admin-system\src\router\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// 路由模块

import { createRouter, createWebHashHistory } from 'vue-router'
import np from 'nprogress'
import store from '@/store/index.js'
// 路由匹配规则
const routes = [
  {
    path: '/login',
    component: () => import('@/views/login.vue')
  },
  {
    path: '/',
    redirect: '/home',
  },
  {
    path: '/home',
    name: 'admin',
    component: () => import('@/views/home.vue'),
    children: [
      {
        path: '/home',
        name: '/home',
        component: () => import('@/views/homeIndex.vue'),
        meta: {
          title: '后台首页'
        }
      },
      {
        path: '/image/list',
        name:'/image/list',
        component: () => import('@/views/picList.vue'),
        meta: {
          title: '图库管理'
        }
      },
      {
        path: '/manager/list',
        name:'/manager/list',
        component: () => import('@/views/managerList.vue'),
        meta: {
          title: '管理员管理'
        }
      },
    ]
  },
  
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/404.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach(async (to, from, next) => {
  np.start()
  const token = sessionStorage.getItem('token')
  if (token) {
    await store.dispatch('getUserInfo')
  }
  if (token && to.path === '/login') {
    next(from.path ? from.path : '/')
  } else if (!token && to.path !== '/login') {
    next('/login')
  } else {
    next()
  }
})

router.afterEach((to, from, next) => {
  np.done()
})

export default router